//
//  DiaryController.m
//  MyTrip
//
//  Created by zhang on 15/8/22.
//  Copyright (c) 2015年 张益. All rights reserved.
//

#import "DiaryController.h"
#import "DiaryCell.h"
#import "ProjectCell.h"
#import "AsyncGETConnection.h"
#import "Diary.h"
#import "Project.h"
#import "DiaryHeaderView.h"
#import "Desc.h"
#import "DiaryDetailController.h"
#import "ProjectDetailController.h"
#import "SlideController.h"
#import "MJRefresh.h"
#import "DKNightVersion.h"
#import "MBProgressHUD.h"

#define Width self.view.frame.size.width
#define Height self.view.frame.size.height

@interface DiaryController ()<UITableViewDataSource, UITableViewDelegate, DiaryHeaderViewDelegate>

@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *diaryArray;
@property (nonatomic, retain) DiaryHeaderView *header;
@property (nonatomic, retain) NSMutableArray *headerArray;
@property (nonatomic, retain) NSNumber *next;
@property (nonatomic, retain) MBProgressHUD *hud;

@end

@implementation DiaryController

- (void)dealloc
{
    [_header release];
    [_diaryArray release];
    [_table release];
    [_headerArray release];
    [super dealloc];
}


- (instancetype) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.diaryArray = [NSMutableArray array];
        self.headerArray = [NSMutableArray array];
        
    }
    return self;
}

#pragma mark - headerviewDelegate
- (void)clickIndex:(NSIndexPath *)indexPath WithURL:(NSString *)url{
    
    SlideController *slide = [[SlideController alloc] init];
    slide.url = url;
    [self.navigationController pushViewController:slide animated:YES];
    [slide release];
}


#pragma mark - <getMessage>

- (void)getMessage{
    self.hud = [[MBProgressHUD alloc] init];
    [self.view addSubview:_hud];
    [_hud show:YES];
    _hud.labelText = @"正在拼命加载......";
    //    在网络请求之后
    
    __block MBProgressHUD *hud = _hud;
    [AsyncGETConnection asyncGETConnectionWithURLStr:@"http://api.breadtrip.com/v5/index" parameters:nil messageBlock:^(NSData *data) {
        hud.hidden = YES;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *elementsArr = [dic objectForKey:@"elements"];
        self.next = [dic objectForKey:@"next_start"];
        for (NSDictionary *eleDic in elementsArr) {
            NSInteger type = [[eleDic objectForKey:@"type"] integerValue];
            if (type == 1) {
                NSArray *dataArr = [eleDic objectForKey:@"data"];
                NSArray *headerArray = [dataArr firstObject];
                for (NSDictionary *pDic in headerArray) {
                    Desc *desc = [[Desc alloc] init];
                    [desc setValuesForKeysWithDictionary:pDic];
                    [_headerArray addObject:desc];
                }
            }
            if (type == 4) {
                NSArray *dataArr = [eleDic objectForKey:@"data"];
                NSDictionary *dataDic = [dataArr firstObject];
                NSDictionary *user = [dataDic objectForKey:@"user"];
                Diary *diary = [Diary diaryWithPic:[dataDic objectForKey:@"cover_image"] title:[dataDic objectForKey:@"name"] date:[dataDic objectForKey:@"first_day"] dayCount:[dataDic objectForKey:@"day_count"] viewCount:[dataDic objectForKey:@"view_count"] authorImage:[user objectForKey:@"avatar_m"] authorName:[user objectForKey:@"name" ] address:[dataDic objectForKey:@"popular_place_str"] type:4 diaryid:[[dataDic objectForKey:@"id"] integerValue]];
                [_diaryArray addObject:diary];
            }if (type == 5) {
                NSArray *dataArr = [eleDic objectForKey:@"data"];
                NSDictionary *dataDic = [dataArr firstObject];
                Project *project = [Project projectWithPic:[dataDic objectForKey:@"cover"] title:[dataDic objectForKey:@"cover_title"] subtitle:[dataDic objectForKey:@"cover_sub_title"] type:5 url:[dataDic objectForKey:@"url"]];
                [_diaryArray addObject:project];
            }if (type == 7) {
                NSArray *dataArr = [eleDic objectForKey:@"data"];
                NSDictionary *dataDic = [dataArr firstObject];
                Project *project = [Project projectWithPic:[dataDic objectForKey:@"cover"] title:[dataDic objectForKey:@"title"] subtitle:[dataDic objectForKey:@"sub_title"] type:5 url:[dataDic objectForKey:@"url"]];
                [_diaryArray addObject:project];
            }
        }
        _header.diaryHeaderArray = _headerArray;
        [_header createPage];
        [_header.diaryHeader reloadData];
        [_table reloadData];
    }];
    
    
}



#pragma mark - <tableview创建>
- (void)createTable{
    
    self.table = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain] autorelease];
    _table.delegate = self;
    _table.dataSource = self;
    [_table registerClass:[DiaryCell class] forCellReuseIdentifier:@"diary"];
    [_table registerClass:[ProjectCell class] forCellReuseIdentifier:@"project"];
    [_table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_table];
    
    
    self.header = [[DiaryHeaderView alloc] initWithFrame:CGRectMake(0, 0, Width, 200 * OffHeight)];
    _header.delegate = self;
    _table.tableHeaderView = _header;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200 * OffHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_diaryArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    id model = [_diaryArray objectAtIndex:indexPath.row];
    if ([model isKindOfClass:[Diary class]]) {
        DiaryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"diary"];
        Diary *diary = [_diaryArray objectAtIndex:indexPath.row];
        [cell setValueWithDiary:diary];
        return cell;
    }else if ([model isKindOfClass:[Project class]]){
        ProjectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"project"];
        Project *project = [_diaryArray objectAtIndex:indexPath.row];
        [cell setvalueWithProject:project];
        return cell;
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    id model = [_diaryArray objectAtIndex:indexPath.row];
    if ([model isKindOfClass:[Diary class]]) {
        Diary *diary = [_diaryArray objectAtIndex:indexPath.row];
        DiaryDetailController *detail = [[DiaryDetailController alloc] init];
        detail.diary = diary;
        [self.navigationController pushViewController:detail animated:YES];
        [detail release];
    }else if ([model isKindOfClass:[Project class]]){
        Project *project = [_diaryArray objectAtIndex:indexPath.row];
        ProjectDetailController *detail = [[ProjectDetailController alloc] init];
        detail.project = project;
        [self.navigationController pushViewController:detail animated:YES];
        [detail release];
    }
    
}






- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createTable];
    [self getMessage];
    self.navigationController.navigationBar.nightBarTintColor = UIColorFromRGB(0x444444);
    self.navigationItem.leftBarButtonItem.nightTintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem.nightTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:70 / 255.0f green:160 / 255.0f blue:175 / 255.0f alpha:1];
    
    self.navigationItem.title = @"旅行中的点点滴滴";
    
    
    [_table addHeaderWithCallback:^{
        _hud.hidden = NO;
        [AsyncGETConnection asyncGETConnectionWithURLStr:@"http://api.breadtrip.com/v5/index" parameters:nil messageBlock:^(NSData *data) {
            _hud.hidden = YES;
            [_table headerEndRefreshing];
            [_headerArray removeAllObjects];
            [_diaryArray removeAllObjects];
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *elementsArr = [dic objectForKey:@"elements"];
            for (NSDictionary *eleDic in elementsArr) {
                NSInteger type = [[eleDic objectForKey:@"type"] integerValue];
                if (type == 1) {
                    NSArray *dataArr = [eleDic objectForKey:@"data"];
                    NSArray *headerArray = [dataArr firstObject];
                    for (NSDictionary *pDic in headerArray) {
                        Desc *desc = [[Desc alloc] init];
                        [desc setValuesForKeysWithDictionary:pDic];
                        [_headerArray addObject:desc];
                    }
                }
                if (type == 4) {
                    NSArray *dataArr = [eleDic objectForKey:@"data"];
                    NSDictionary *dataDic = [dataArr firstObject];
                    NSDictionary *user = [dataDic objectForKey:@"user"];
                    Diary *diary = [Diary diaryWithPic:[dataDic objectForKey:@"cover_image"] title:[dataDic objectForKey:@"name"] date:[dataDic objectForKey:@"first_day"] dayCount:[dataDic objectForKey:@"day_count"] viewCount:[dataDic objectForKey:@"view_count"] authorImage:[user objectForKey:@"avatar_m"] authorName:[user objectForKey:@"name" ] address:[dataDic objectForKey:@"popular_place_str"] type:4 diaryid:[[dataDic objectForKey:@"id"] integerValue]];
                    [_diaryArray addObject:diary];
                }if (type == 5) {
                    NSArray *dataArr = [eleDic objectForKey:@"data"];
                    NSDictionary *dataDic = [dataArr firstObject];
                    Project *project = [Project projectWithPic:[dataDic objectForKey:@"cover"] title:[dataDic objectForKey:@"cover_title"] subtitle:[dataDic objectForKey:@"cover_sub_title"] type:5 url:[dataDic objectForKey:@"url"]];
                    [_diaryArray addObject:project];
                }if (type == 7) {
                    NSArray *dataArr = [eleDic objectForKey:@"data"];
                    NSDictionary *dataDic = [dataArr firstObject];
                    Project *project = [Project projectWithPic:[dataDic objectForKey:@"cover"] title:[dataDic objectForKey:@"title"] subtitle:[dataDic objectForKey:@"sub_title"] type:5 url:[dataDic objectForKey:@"url"]];
                    [_diaryArray addObject:project];
                }
            }
            _header.diaryHeaderArray = _headerArray;
            [_header createPage];
            [_header.diaryHeader reloadData];
            [_table reloadData];
        }];
    }];
    
    [_table addFooterWithCallback:^{
        _hud.hidden = NO;
        //        http://api.breadtrip.com/v5/index/?next_start=2386609217
        [AsyncGETConnection asyncGETConnectionWithURLStr:[NSString stringWithFormat:@"http://api.breadtrip.com/v5/index/?next_start=%@", self.next] parameters:nil messageBlock:^(NSData *data) {
            _hud.hidden = YES;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *elementsArr = [dic objectForKey:@"elements"];
            self.next = [dic objectForKey:@"next_start"];
            for (NSDictionary *eleDic in elementsArr) {
                NSInteger type = [[eleDic objectForKey:@"type"] integerValue];
                if (type == 4) {
                    NSArray *dataArr = [eleDic objectForKey:@"data"];
                    NSDictionary *dataDic = [dataArr firstObject];
                    NSDictionary *user = [dataDic objectForKey:@"user"];
                    Diary *diary = [Diary diaryWithPic:[dataDic objectForKey:@"cover_image"] title:[dataDic objectForKey:@"name"] date:[dataDic objectForKey:@"first_day"] dayCount:[dataDic objectForKey:@"day_count"] viewCount:[dataDic objectForKey:@"view_count"] authorImage:[user objectForKey:@"avatar_m"] authorName:[user objectForKey:@"name" ] address:[dataDic objectForKey:@"popular_place_str"] type:4 diaryid:[[dataDic objectForKey:@"id"] integerValue]];
                    [_diaryArray addObject:diary];
                }if (type == 5) {
                    NSArray *dataArr = [eleDic objectForKey:@"data"];
                    NSDictionary *dataDic = [dataArr firstObject];
                    Project *project = [Project projectWithPic:[dataDic objectForKey:@"cover"] title:[dataDic objectForKey:@"cover_title"] subtitle:[dataDic objectForKey:@"cover_sub_title"] type:5 url:[dataDic objectForKey:@"url"]];
                    [_diaryArray addObject:project];
                }if (type == 7) {
                    NSArray *dataArr = [eleDic objectForKey:@"data"];
                    NSDictionary *dataDic = [dataArr firstObject];
                    Project *project = [Project projectWithPic:[dataDic objectForKey:@"cover"] title:[dataDic objectForKey:@"title"] subtitle:[dataDic objectForKey:@"sub_title"] type:5 url:[dataDic objectForKey:@"url"]];
                    [_diaryArray addObject:project];
                }
            }
            [_table reloadData];
            [_table footerEndRefreshing];
        }];
        
    }];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
